package com.umfwechat.lightprogram.controller.pos;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.lightprogram.controller.selfdeploy.ShowImgController;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.StringUtil;

/*********************************************
 * MerchantProductPosPhotoController.java
 * Author: Vermouth.yf
 * Created on: 2017-5-27
 *
 * Details:  《开通pos上传照片》 接口
 ********************************************/


@Controller
@RequestMapping("/merchantProductDeploy")
public class MerchantProductPosPhotoController {
	
	private static Logger logger = LoggerFactory.getLogger(MerchantProductPosPhotoController.class);
	
//	  private static String IMG_HTTP_ADDRESS = "http://10.10.133.92:8080/umfWeChatPlat/merchantDeploy/showImg?name=";
//	  private static String IMG_FILE_ADDRESS = "D:/SaasImg/";
	  
	//开发环境打开下面两行，关闭上面两行
	  private static String IMG_HTTP_ADDRESS = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","img.http.url", ""); //http://10.10.67.77:8180/umfWeChatPlat/merchantDeploy/showImg?name=
	  private static String IMG_FILE_ADDRESS = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","posUpload.img.fileaddress", "");  ///usr/mpsp/duizhang/qualification/pos/
	  
	
	/**
	 * 提交图片信息，并返回图片路径  imgUrl
	 *    img
          storeId
          imgName   输入
          
          retCode 
          retMsg    输出
          imgUrl
	 * 
	 * 
	 * Author: Vermouth.yf 
	 * Date: 2017-5-27 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/openPosUpload",produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject openPosUpload(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("----*---------*--开通pos上传照片，开始--*---------*--");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		JSONObject resultJson = new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		logger.info("----#---------#--pos upload img --#---------#--" + reqJSON);
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请求参数不足");
			logger.info("----#---------#--pos上传照片数据转换异常--#---------#--" + e);
			return resultJson;
		}
		String imgHttpUrl = IMG_HTTP_ADDRESS;	//图片服务器Http地址
		String imgFileUrl = IMG_FILE_ADDRESS;	//获取图片服务器存储地址
		logger.info("----*---------*--开通pos上传照片信息地址：--*---------*--" + imgHttpUrl + "--*---------*--" + imgFileUrl);
		if(StringUtil.isEmpty(imgHttpUrl) || StringUtil.isEmpty(imgFileUrl)){	//获取配置信息失败则返回提示信息
			resultMap.put("retCode", "0001");
			resultMap.put("retMsg", "获取照片信息失败");
			return JSONObject.fromObject(resultMap);
		}
		
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		String storeId = null;	//店铺编号
		String imgName = null;  //图片名称   由我这边定义
		FileItem file = null;	//图片
		try{
		 factory = new DiskFileItemFactory();	//创建一个DiskFileItemFactory工厂  
		 upload = new ServletFileUpload(factory);	//创建一个文件上传解析器  
		 upload.setHeaderEncoding("UTF-8");
		 imgName = UUID.randomUUID().toString().replace("-", "") + ".jpg";   
		//--------------------------正式生产---------------------------
		List<FileItem> items = upload.parseRequest(request);	
		for (FileItem item : items) {
			String name = item.getFieldName();
			logger.info("name:" + name + ",isFormField：" +item.isFormField() ); 
			if ("file".equals(name)) {
				file = item;
		  }
		}
		storeId = (String)json.get("storeId");
		
		}catch(Exception e){
			logger.info("pos图片上传接口，获取图片失败。");
			resultMap.put("retCode", "0001");
			resultMap.put("retMsg", "获取请求失败"+e.getMessage());
			return JSONObject.fromObject(resultMap);
		}
		//--------------------------正式生产---------------------------
		
		if (StringUtil.isEmpty(storeId) || file == null) {
			resultMap.put("retCode", "0001");
			resultMap.put("retMsg", "请求参数不足");
			return JSONObject.fromObject(resultMap);
		}
		
		String imageUrl = imgFileUrl+storeId+"/"+imgName;	//TODO 生成图片的URL 比如  /yangfan/storeId/xadsf.jpg
		logger.info("----#---------#--return URL，start--#---------#--"+imageUrl);
		/**
		 *  注意：  这里产生的回显地址   pos提交接口需要的仅仅是 后面那一串本地路径  
		 * */
		String imgUrl = ShowImgController.getImgUrl(file, imageUrl, imgHttpUrl);  // 文件  本地路径  远程路径
		logger.info("----#---------#--return URL，end--#---------#--" + imgUrl);
		
		if(StringUtil.isEmpty(imageUrl)){
			resultMap.put("retCode", "0001");
			resultMap.put("retMsg", "图片上传失败");
			return JSONObject.fromObject(resultMap);
		}
		
		resultMap.put("retCode", "0000");
		resultMap.put("retMsg", "图片上传成功");
        resultMap.put("imgUrl", imgUrl);		
        return JSONObject.fromObject(resultMap);      
	}
}
